package cn.rubintry.bug.hunting.common.password

import android.text.NoCopySpan
import android.text.Spannable
import android.text.method.PasswordTransformationMethod
import android.view.View
import java.lang.ref.WeakReference


/**
 * 基于原先的实现，修改了显示过程，现在全程不显示明文
 */
class SafePasswordTransformationMethod : PasswordTransformationMethod() {

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        if (s is Spannable) {
            val sp = s
            val vr: Array<ViewReference> = sp.getSpans(
                0, s.length, ViewReference::class.java
            )
            if (vr.size == 0) {
                return
            }

            var v: View? = null
            var i = 0
            while (v == null && i < vr.size) {
                v = vr[i].get()
                i++
            }
            if (v == null) {
                return
            }
            //关键点，这里不要show，否则容易被看到明文，所以注释掉
//            val pref: Int = TextKeyListener.getInstance().getPrefs(v.context)
//            if (pref and TextKeyListener.SHOW_PASSWORD !== 0) {
//                if (count > 0) {
//                    PasswordTransformationMethod.removeVisibleSpans(sp)
//                    if (count == 1) {
//                        sp.setSpan(
//                            PasswordTransformationMethod.Visible(sp, this), start, start + count,
//                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
//                        )
//                    }
//                }
//            }
        }
    }


    private class ViewReference(v: View?) : WeakReference<View?>(v),
        NoCopySpan

}